package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.alibaba.fastjson.JSON;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.util.DateUtil;
import com.software.boot.common.util.StringUtil;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.CrmClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.CrmSysClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.request.SyncCrmCreateClueRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.request.SyncCrmUpdateClueRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.response.SyncCrmCreateResponse;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueInitial;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.DealerCustomerFollowRecord;
import com.tencent.iov.cowin.befsale.clue.service.clue.CrmService;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.software.boot.common.entity.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Describe: crm服务层
 * @author: zly
 * @created: 2022-01-23
 * @version: 1.0
 */
@Service
@Slf4j
public class CrmServiceImpl implements CrmService {

    @Autowired
    private CrmSysClient crmSysClient;
    @Autowired
    private CrmClient crmClient;

    @Autowired
    private DealerCustomerFollowRecordService dealerCustomerFollowRecordService;

    @Value("${crm.token.sourceID:1604635381000905011}")
    private Long sourceID;
    @Value("${crm.token.userName:scrm}")
    private String userName;
    @Value("${crm.token.passWord:@Cowin2021}")
    private String passWord;

    /**
     * add by zly
     * 2022-01-23
     * crm服务获取token
     * @return
     */
    @Override
    public String getCrmToken() {
        String token="";
        try {
            log.info("获取token,sourceID={},userName={},passWord={}",sourceID,userName,passWord);
            Response tokenRes = crmSysClient.getCrmToken(sourceID,userName,passWord);
            log.info("获取token,sourceID={},userName={},passWord={},返回信息={}",sourceID,userName,passWord,JSON.toJSONString(tokenRes));
            if(tokenRes!=null&&tokenRes.getData()!=null){
                token=tokenRes.getData().toString();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    /**
     * add by zly
     * 2022-01-22
     * 线索定时同步--定时同步crm新增
     * @param request
     * @return status 1:新建 2:合并(对应SCRM的清洗无效5)
     */
   public SyncCrmCreateResponse clueInitialDataToCrm(SyncCrmCreateClueRequest request, ClueInitial c){
       log.info("企微创建线索，手机号={},name={},调用crm新增接口开始时间startTime={}",c.getPhone(),c.getName(), DateUtil.toDateString(new Date(), DateUtil.BEANTECHS_DATE_FORMAT_PASS_SSSSSSS));
       SyncCrmCreateResponse crmRes=null;
       String checkStr= this.checeCrmInsertRequest(request);
       try {
           crmRes= crmClient.clueInitialDataToCrm(request,getCrmToken());
           log.info("定时器调用crm接口进行线索新增，入参request={}, 必填参数验证={},返回信息toCrmResponse={}",JSON.toJSONString(request),checkStr,JSON.toJSONString(crmRes));
           if(crmRes!=null&&!StringUtils.isEmpty(crmRes.getLeadId())){
               c.setCrmClueId(crmRes.getLeadId());
               Integer status= crmRes.getStatus();
               c.setStatus(status==2?InitialStatusEnum.STATUS_CRM.getCode():status);
           }else{
               c.setStatus(InitialStatusEnum.STATUS_CRM.getCode());
           }
       }catch (Exception e){
           crmRes=new SyncCrmCreateResponse();
           c.setStatus(InitialStatusEnum.STATUS_CRM.getCode());
           crmRes.setMsg("调用crm新增接口出错，catch错误信息="+org.apache.commons.lang.StringUtils.substring(e.getMessage(),0,500));
           e.printStackTrace();
       }finally {
           c.setCleanType(InitialCleanTypeEnum.TYPE_DEAL_WITH.getCode());
           if(c.getStatus()==InitialStatusEnum.STATUS_CRM.getCode()|| StringUtil.isEmpty(c.getCrmClueId())){
               //添加一条清洗失效的记录
               AddCustomerFollowRecordRequest recordRequest= OemCustomerFollowRecordAssembler.transformVOToPO(request,AddCustomerFollowRecordRequest.class);
               recordRequest.setId(null);
               recordRequest.setStatus(FollowRecordStatusEnum.INIT.getCode());
               recordRequest.setSecondStatus(FollowRecordSecondStatusEnum.INIT_INVALID.getCode());
               recordRequest.setCusId(-1l);
               recordRequest.setClueId(c.getId());
               recordRequest.setSyncRemark("入参="+JSON.toJSONString(request)+"; 必填参数验证="+checkStr+";返回信息="+JSON.toJSONString(crmRes));
               dealerCustomerFollowRecordService.insert(recordRequest);
           }
           log.info("企微创建线索，手机号={},name={},调用crm新增接口结束时间startTime={}",c.getPhone(),c.getName(), DateUtil.toDateString(new Date(), DateUtil.BEANTECHS_DATE_FORMAT_PASS_SSSSSSS));
           return crmRes;
       }
    }

    /**
     * add by zly
     * 2022-01-23
     * 线索定时同步--定时同步crm修改
     * @param request
     * @return
     */
    @Override
    public SyncCrmCreateResponse clueInitialDataToCrmUpdate(SyncCrmUpdateClueRequest request) {
        try {
            //crm只接收 交车，战败状态的线索 进行更新
            log.info("定时器调用crm接口进行线索修改，入参request={}",JSON.toJSONString(request));
            SyncCrmCreateResponse updateRes= crmClient.clueInitialDataToCrmUpdate(request,getCrmToken());
            log.info("定时器调用crm接口进行线索修改，入参request={}, 返回信息toCrmResponse={}",JSON.toJSONString(request),JSON.toJSONString(updateRes));
            //修改该条记录--syncRemark字段
            DealerCustomerFollowRecord recordRequest=new DealerCustomerFollowRecord();
            recordRequest.setId(request.getRecordId());
            recordRequest.setSyncRemark("调用crm接口同步战败，交车，战败激活，入参="+JSON.toJSONString(request)+"; 返回信息="+JSON.toJSONString(updateRes));
            dealerCustomerFollowRecordService.update(recordRequest);
        }catch (Exception e){
            //修改该条记录--syncRemark字段
            DealerCustomerFollowRecord recordRequest=new DealerCustomerFollowRecord();
            recordRequest.setId(request.getRecordId());
            recordRequest.setSyncRemark("调用crm接口同步战败，交车，战败激活，入参="+JSON.toJSONString(request)+"; 方法catch出错="+org.apache.commons.lang.StringUtils.substring(e.getMessage(),0,500));
            dealerCustomerFollowRecordService.update(recordRequest);
            e.printStackTrace();
        }
        return null;
    }


    private String checeCrmInsertRequest(SyncCrmCreateClueRequest dataToCrm){
        StringBuffer sb=new StringBuffer();
        if(StringUtils.isEmpty(dataToCrm.getCarSeries())){
            sb.append("--carSeries不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getProvince())){
            sb.append("--province不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getCity())){
            sb.append("--city不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getDealers())){
            sb.append("--dealers不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getUserName())){
            sb.append("--userName不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getMobile())){
            sb.append("--mobile不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getSiteCode())){
            sb.append("--siteCode不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getChannel())){
            sb.append("--channel不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getActive())){
            sb.append("--active不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getSourceCompany())){
            sb.append("--sourceCompany不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getSeriesCode())){
            sb.append("--seriesCode不能为空");
        }
        if(StringUtils.isEmpty(dataToCrm.getSeriesName())){
            sb.append("--seriesName不能为空");
        }
        return sb.toString();
    }

}
